package com.metadata_system.common.db.mapper;

import com.metadata_system.common.db.entity.ProjectLog;
import com.metadata_system.common.dto.ProjectLogCount;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import tk.mybatis.mapper.common.Mapper;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

public interface ProjectLogMapper extends Mapper<ProjectLog> {
    @Select("select last_insert_id()")
    Integer getLastInsertId();
    /**
     * 统计用户未读消息数量
     * @param userId 用户ID
     * @return 包含两种未读数量的Map
     */
    @Select("SELECT " +
            "project_id AS projectId, " +
            "CAST(IFNULL(SUM(CASE WHEN is_handler_user_read = 0 THEN 1 ELSE 0 END),0) AS SIGNED) as handler, " +
            "CAST(IFNULL(SUM(CASE WHEN is_user_read = 0 THEN 1 ELSE 0 END),0) AS SIGNED) as apply " +
            "FROM md_project_log " +
            "WHERE (user_id = #{userId} OR handler_user_id = #{userId} ) group by project_id")
    List<ProjectLogCount> countProjectUnreadMessages(@Param("userId") Integer userId);


    @Update("UPDATE md_project_log " +
            " SET " +
            "        is_user_read = CASE " +
            "            WHEN user_id = #{userId} THEN 1 " +
            "            ELSE is_user_read " +
            "        END," +
            "        is_handler_user_read = CASE " +
            "            WHEN handler_user_id = #{userId} THEN 1 " +
            "            ELSE is_handler_user_read " +
            "        END" +
            "    WHERE user_id = #{userId} OR handler_user_id = #{userId}")
    void readAll(@Param("userId") Integer userId);

    @Update("UPDATE md_project_log set is_user_read = 1 where user_id = #{userId} and id = #{id}")
    void readProjectApply(@Param("userId") Integer userId,@Param("id") Integer id);

    @Update("UPDATE md_project_log set is_handler_user_read = 1 where handler_user_id = #{userId} and id = #{id}")
    void readProjectHandler(@Param("userId") Integer userId,@Param("id") Integer id);
}